<template>
  <div class="app-container">

    <!-- 顶部查询表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="100px">
      <el-form-item label="创建时间">
        <el-date-picker v-model="createDate" type="daterange" range-separator="—" start-placeholder="开始时间"
          end-placeholder="结束时间" format="yyyy-MM-dd" value-format="yyyy-MM-dd" clearable />
      </el-form-item>
      <el-form-item label="发货单号" prop="shipmentCode">
        <el-input v-model="queryParams.shipmentCode" placeholder="请输入发货单号" clearable style="width: 200px"/>
      </el-form-item>
      <el-form-item label="平台单号" prop="platformOrderCode">
        <el-input v-model="queryParams.platformOrderCode" placeholder="请输入平台单号" clearable style="width: 200px"/>
      </el-form-item>
      <el-form-item label="订单编号" prop="orderCode">
        <el-input v-model="queryParams.orderCode" placeholder="请输入订单编号" clearable style="width: 200px"/>
      </el-form-item>
      <el-form-item label="店铺名称" prop="shopId">
        <el-select v-model="queryParams.shopId" placeholder="请选择店铺" clearable>
          <el-option v-for="item in shopList" :key="item.id" :label="item.shopName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="仓库名称" prop="warehouseId">
        <el-select v-model="queryParams.warehouseId" placeholder="请选择仓库" clearable filterable style="width: 200px">
          <el-option v-for="item in warehouseList" :key="item.warehouseName" :label="item.warehouseName" :value="item.warehouseName"/>
        </el-select>
      </el-form-item>
      <el-form-item label="物流公司" prop="expressCompany">
        <el-select v-model="queryParams.expressCompany" placeholder="请选择物流公司" clearable style="width: 100%">
          <el-option v-for="item in expressCompanyOptions" :key="item.id" :label="item.platformName" :value="item.platformName" />
        </el-select>
      </el-form-item>
      <el-form-item label="物流单号" prop="expressCode">
        <el-input v-model="queryParams.expressCode" placeholder="请输入物流单号" clearable style="width: 200px"/>
      </el-form-item>
      <el-form-item label="发货状态" prop="shipStatus">
        <el-select v-model="queryParams.shipStatus" placeholder="请选择发货状态" clearable filterable style="width: 200px">
          <el-option label="已发货" value="SHIPPED"/>
          <el-option label="未发货" value="UNSHIPPED"/>
          <el-option label="锁定" value="LOCKED"/>
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态" prop="orderStatus">
        <el-select v-model="orderStatus" placeholder="请选择订单状态" clearable>
           <el-option
              v-for="dict in dict.type.order_progress"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
        </el-select>
      </el-form-item>
        <!-- 发货单是否作废 -->
      <el-form-item label="发货单作废" prop="isCancel">
        <el-checkbox v-model="isCancel" />
      </el-form-item>
      <el-form-item label="是否拦截">
        <el-checkbox v-model="intercepted" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮组 -->
    <div class="operation-group">
      <el-button size="mini" @click="handlePartialDelivery">发货</el-button>
      <el-button size="mini" @click="handleForceDelivery">强制发货</el-button>
      <el-button  size="mini" @click="handleDeliveryImport">发货导入</el-button>
      <el-button  size="mini" @click="handleExport">导出</el-button>
    </div>

    <!-- 主表格 -->
    <div class="app-container-main">
      <vxe-table
        border
        stripe
        v-loading="loading"
        ref="tableRef"
        size="small"
        header-align="center"
        :row-config="rowConfig" 
        :column-config="columnConfig"
        :data="mainTableData"
        @checkbox-change="mainCheckboxChange"
        @checkbox-all="mainCheckboxAll"
        @cell-click="cellClickEvent"
      >
        <vxe-column type="checkbox" width="80" fixed="left" drag-sort />
        <vxe-column type="seq" title="序号" width="50" fixed="left" />
        <vxe-column field="shipmentCode" title="发货单号" width="120"  fixed="left" />
        <vxe-column field="platformOrderCode" title="平台单号" width="120" />
        <vxe-column field="deliveryStatus" title="发货状态" align="center" width="80"></vxe-column>
        <vxe-column field="expressBillPrinter" title="物流单打印" align="center" width="90">
          <template v-slot="{ row }">
            <span>{{ row.expressBillPrinter && row.expressBillPrinter !== null ? '是' : '否' }}</span>
          </template>
        </vxe-column>
        <vxe-column field="shipmentBillPrinter" title="发货单打印" align="center" width="90">
          <template v-slot="{ row }">
            <span>{{ row.shipmentBillPrinter && row.shipmentBillPrinter !== null ? '是' : '否' }}</span>
            <!-- <el-checkbox :v-model="row.shipmentBillPrinter ? true : false" disabled /> -->
          </template>
        </vxe-column>
        <vxe-column field="collect" title="货到付款?" width="80">
          <template v-slot="{ row }">
            <span>{{ row.collect === '1' ? '是' : '否' }}</span>
          </template>
        </vxe-column>
        <vxe-column field="multiPackage" title="多包裹/子母件" width="120">
          <template #default="{ row }">
              <span>{{ row.multiPackage && row.multiPackage !== null ? '是' : '否' }}</span>
          </template>
        </vxe-column>
        <vxe-column field="expressBillPrinter" title="物流单打印人" width="100"></vxe-column>
        <vxe-column field="shipmentBillPrinter" title="发货单打印人" width="100"></vxe-column>
        <vxe-column field="expressBillPrintSeq" title="物流单打印批次-流水号" width="160" />
        <vxe-column field="shipmentBillPrintSeq" title="发货单打印批次-流水号" width="160" />
        <vxe-column field="expressCode" title="物流单号" width="140" />
        <vxe-column field="shopName" title="店铺" width="120" />
        <vxe-column field="clientName" title="会员" width="100" />
        <vxe-column field="consignee" title="收货人" width="100" />
        <vxe-column field="productName" title="商品信息" width="150" />
        <vxe-column field="itemQuantity" title="商品数量？" width="80" align="right" />
        <vxe-column field="itemWeight" title="商品重量？" width="80" align="right" />
        <vxe-column field="itemVolume" title="商品体积？" width="80" align="right" />
        <vxe-column field="warehouseName" title="仓库" width="120" />
        <vxe-column field="expressCompany" title="物流公司" width="120" />
        <vxe-column field="buyerRemark" title="买家备注" width="150" show-overflow />
        <vxe-column field="sellerRemark" title="卖家备注" width="150" show-overflow />
        <vxe-column field="secRemark" title="二次备注" width="150" show-overflow />
        <vxe-column field="extInfo" title="附加信息" width="150" show-overflow />
        <vxe-column field="secAuditBy" title="财审人" width="100" />
        <vxe-column field="prepareBy" title="配货人" width="100" />
        <vxe-column field="prepareTime" title="配货时间" width="150" />
        <vxe-column field="payTime" title="支付时间" width="150" />
        <vxe-column field="intercepted" title="是否拦截" width="100">
          <template v-slot="{ row }">
              <span>{{ row.intercepted && row.intercepted !== null ? '是' : '否' }}</span>
          </template>
        </vxe-column>
        <vxe-column field="cancelled" title="是否作废" width="100">
          <template v-slot="{ row }">
            <span>{{ row.cancelled && row.cancelled !== null ? '是' : '否' }}</span>
          </template>
        </vxe-column>
        <vxe-column field="deliveryCanceled" title="发货单作废状态？" width="120">
          <template v-slot="{ row }">
            <span>{{ row.deliveryCanceled && row.deliveryCanceled !== null ? '是' : '否' }}</span>
          </template>
        </vxe-column>
      </vxe-table>
      
      <!-- 主表格分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <!-- 底部Tab区域 -->
    <div class="app-container-footer">
        <el-tabs v-model="activeTab" type="border-card">
          <el-tab-pane label="基本信息" name="orderDetail">
            <OrderDetail :cellId="cellId" />
          </el-tab-pane>
          <el-tab-pane label="商品明细" name="itemDetail">
            <ItemDetail :cellId="cellId" />
          </el-tab-pane>
          <el-tab-pane label="收货信息" name="receiverInfo">
            <ReceiverInfo :cellId="cellId" />
          </el-tab-pane>
          <el-tab-pane label="操作日志" name="opLog">
            <OpLog :cellId="cellId" />
          </el-tab-pane>
        </el-tabs>
    </div>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
        <el-upload
            ref="upload"
            :limit="1"
            accept=".xlsx, .xls"
            :headers="upload.headers"
            :action="upload.url + '?updateSupport=' + upload.updateSupport"
            :disabled="upload.isUploading"
            :auto-upload="false"
            drag
        >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip text-center" slot="tip">
                <span>仅允许导入xls、xlsx格式文件。</span>
                <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
            </div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitFileForm">确 定</el-button>
            <el-button @click="upload.open = false">取 消</el-button>
        </div>
    </el-dialog>
  </div>
</template>

<script>
import OrderDetail from './components/orderDetail.vue';
import ItemDetail from './components/itemDetail.vue';
import ReceiverInfo from './components/receiverInfo.vue';
import OpLog from './components/opLog.vue';
import { getToken } from "@/utils/auth";

import { listPrepare } from "@/api/mes/sales/prepare";
import { listWarehouse } from "@/api/mes/wm/warehouse";
import { listShopBasic } from "@/api/mes/sales/shopBasic";
import { listPlatforms } from "@/api/mes/sales/platform";

import {
  saleShip,
  forceSaleShip
} from "@/api/mes/sales/print";


export default {
  name: "Prepare",
  components: {
    OrderDetail,
    ItemDetail,
    ReceiverInfo,
    OpLog
  },
  dicts: [ 'platform_type', 'order_progress',],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      columnConfig: {
        drag: true,
        resizable: true,
        storage: true,
        sortConfig: {
          trigger: "cell",
          remote: true,
        },
        align: "center",
        headerAlign: "center",
      },
      rowConfig: {
        drag: true,
        keyField: "id",
        isHover: true,
        isCurrent: true,
      },
      // 店铺选项
      shopList: [],
      warehouseList: [],
      expressCompanyOptions:[],
      // 主表格数据
      mainTableData: [],
      // 底部Tab
      activeTab: 'orderDetail',
      // 当前选中行ID
      cellId: null,
      upload: {
        open: false,
        title: '',
        isUploading: false,
        updateSupport: 0,
        headers: { Authorization: 'Bearer ' + getToken() },
        url: process.env.VUE_APP_BASE_API + '/mes/md/shop/importData'
      },
      createDate: this.getDefaultDateRange(),
      isCancel: false,
      intercepted: false,
    };
  },
  created() {
    this.getList();
    this.getShopList();
    this.getWarehouseList();
    setTimeout(() => {
      this.getLogisticsCompanyList()
    }, 100);
  },
  methods: {
    getDefaultDateRange() {
      const today = new Date();
      const thirtyDaysAgo = new Date();
      thirtyDaysAgo.setDate(today.getDate() - 30);
      const formatDate = (date) => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        return `${year}-${month}-${day}`;
      };
      return [formatDate(thirtyDaysAgo), formatDate(today)];
    },
    // 获取物流公司
    getLogisticsCompanyList(){
      listPlatforms({
        platformType: this.dict.type.platform_type.filter(item => item.label === '物流平台')[0].value,
        enabled: 1,
        pageNum: 1,
        pageSize: 9999,
      }).then(response => {
        this.expressCompanyOptions = response.rows;
      })
    },
    // 仓库下拉数据
    getWarehouseList(){
      listWarehouse({
        pageNum: 1,
        pageSize: 9999,
      }).then(response => {
        this.warehouseList = response.rows;
      })
    },
    // 店铺下拉数据
    getShopList(){
      listShopBasic({
        enabled: 1,
        pageNum: 1,
        pageSize: 9999
      }).then(response => {
        this.shopList = response.rows;
      })
    },

    /** 查询列表 */
    getList() {
      this.loading = true;
      // 处理日期范围
      if (
        this.createDate &&
        this.createDate.length === 2
      ) {
        this.queryParams.startDate = this.createDate[0];
        this.queryParams.endDate = this.createDate[1];
      }
      this.queryParams.isCancel = this.isCancel ? 1 : 0;
      this.queryParams.intercepted = this.intercepted ? 1 : 0;
      listPrepare(this.queryParams)
        .then(response => {
          if(response.code === 200) {
            this.mainTableData = response.rows;
            this.total = response.total;
            this.$nextTick(() => {
              if (this.mainTableData.length > 0) {
                this.$refs.tableRef.setCurrentRow(this.mainTableData[0]);
              }
            });
            if (response.rows?.length > 0) {
              this.cellId = response.rows[0].id;
            }
          } 
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      };
      this.createDate = this.getDefaultDateRange();
      this.isCancel = false;
      this.intercepted = false;
      this.handleQuery();
    },

    /** 发货操作 */
    handlePartialDelivery() {
      if (!this.ids.length) {
        this.$message.warning('请选择发货单');
        return;
      }
      this.$confirm('确定要发货选中的记录吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        saleShip(this.ids).then(response => {
          if (response.code === 200) {
            if(response.data && response.data !== null) {
              this.$message.warning(response.data );
            } else {
              this.$message.success('发货成功');
            }
            this.getList();
          }
        });
      });
    },

    /** 强制发货操作 */
    handleForceDelivery() {
      if (!this.ids.length) {
        this.$message.warning('请选择发货单');
        return;
      }
      this.$confirm('确定要强制发货选中的记录吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        forceSaleShip(this.ids).then(response => {
          if (response.code === 200) {
            this.$message.success('强制发货成功');
            this.getList();
          }
        })
      });
    },
    

    /** 发货导入操作 */
    handleDeliveryImport() {
      this.upload.open = true;
      this.upload.title = '发货导入';
    },

    /** 导入模板操作 */
    importTemplate() {
      this.$message.info('请联系管理员获取导入模板');
    },

    /** 发货导出操作 */
    handleExport() {
      if (!this.ids.length) {
        this.$message.warning('请选择发货单');
        return;
      }
      this.$message.info('功能开发中');
    },

    /** 主表格 Checkbox 事件 */
    mainCheckboxChange({ records }) {
      this.ids = records.map(item => item.id);
    },
    mainCheckboxAll({ records }) {
      this.ids = records.map(item => item.id);
    },
    /** 单元格点击事件 */
    cellClickEvent({ row }) {
      if (row && row.id !== this.cellId) {
        this.cellId = row.id;
      }
    },
    submitFileForm() {
      this.$message.info('功能开发中');
      // this.$refs.upload.submit();
      // this.upload.isUploading = true;
      // this.$refs.upload.$on('success', (response) => {
      //   this.upload.isUploading = false;
      //   if (response.code === 200) {
      //     this.$message.success('导入成功');
      //     this.upload.open = false;
      //     this.getList();
      //   } else {
      //     this.$message.error(response.msg || '导入失败');
      //   }
      // });
      // this.$refs.upload.$on('error', () => {
      //   this.upload.isUploading = false;
      //   this.$message.error('导入失败');
      // });
    }
  }
};
</script>

<style lang="scss" scoped>
.app-container-footer {
  margin-top: 20px;
}
.mb8 {
  margin-bottom: 8px;
}
</style>
